package com.tceasy.gateway.filter;

import com.tceasy.gateway.Constants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by zhanghuan on 2016/4/12.
 */
public class LoginCheckFilter implements Filter {

    Logger logger= LoggerFactory.getLogger(LoginCheckFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession();
        /*开放平台对开发者暴露的接口不需要登录验证*/
        if(servletRequest.getServletPath().lastIndexOf("/gateway")==0){
            chain.doFilter(request, response);
            return;
        }
        //获得用户请求的URI
        String path = servletRequest.getRequestURI();
        String username = (String) session.getAttribute(Constants.USER_IN_SESSION);

        if(Constants.isIgnore(path)) {
            chain.doFilter(request, response);
            return;
        }
        // 判断如果没有取到员工信息,就跳转到登陆页面
        if (StringUtils.isBlank(username)) {
           // 跳转到登陆页面
           servletResponse.sendRedirect(servletRequest.getContextPath()+"/login.jsp");
        } else {
           // 已经登陆,继续此次请求
           chain.doFilter(request, response);
        }
    }


    @Override
    public void destroy() {

    }
}
